<?php
/** Little script to calculate distance between 2 zipcodes. The zipcodes are put in a matrix.
 * 	Row 1 and column 1 define the zipcodes and all the rest of the fields are to be populated with traveldistances in minutes.
 * 	The zipcodes can be populated by manually typing them or uploading a CSV file which contains the Horizontal zipcode as first field and vertical zipcode as second field.
 * 	Using Google Maps API V3 and based on some javascript that was posted online (go to the @see url).
 *
 * 	IMPORTANT!
 * 	This script posts excessive amounts of input fields to the script write_excel.php, the PHP.ini configuration needs to allow this.
 * 	Since PHP 5.3.9 a new PHP.ini variable was introduced - max_input_vars - to limit the amounts of fields that can be posted (security considerations).
 * 	This will default to 1000, which will not be enough. A value of 5000 is recommended.
 * 	This can either be defined with a .htaccess file or globally using php.ini.
 *
 *  @author		Jos Nienhuis
 *  @since		15-08-2013
 *  @version	2.0
 * 	@copyright 	Copyright (c) 2013 Jos Nienhuis
 *  @see		http://briancray.com/posts/calculate-driving-distance-google-maps-api
 */

$amountOfPostalCodes = 0;
$cellIndex = 1;

if($_SERVER['REQUEST_METHOD'] == 'POST'){
	$csv = parse_csv(trim(file_get_contents($_FILES['csvfile']['tmp_name'])), ';');
	$amountOfPostalCodes = count($csv);
}
else if(isset($_GET['amount'])){
	$amountOfPostalCodes = intval($_GET['amount']);
}

/** This function is more compatible with csv exports from Excel than the implementation of native PHP str_getcsv.
 * 	Based on a comment on the PHP site for str-getcsv, take a look at the @see tag
 * 	@param		string			$csv_string			The string to be used as source.
 * 	@param		string			$delimiter			The delimiter that seperates fields in the CSV, defaults to ','.
 * 	@param		bool			$skip_empty_lines	Whether or not to skip empty fields, defaults to true.
 * 	@param		bool			$trim_fields		Whether or not to trim each field's value, defaults to true.
 *  @since		15-08-2013
 *  @version	1.0
 *  @see		http://php.net/manual/en/function.str-getcsv.php
 */
function parse_csv($csv_string, $delimiter = ",", $skip_empty_lines = true, $trim_fields = true){
    $enc = preg_replace('/(?<!")""/', '!!Q!!', $csv_string);
    $enc = preg_replace_callback(
        '/"(.*?)"/s',
        function ($field) {
            return urlencode(utf8_encode($field[1]));
        },
        $enc
    );
    $lines = preg_split($skip_empty_lines ? ($trim_fields ? '/( *\R)+/s' : '/\R+/s') : '/\R/s', $enc);

    return array_map(
        function ($line) use ($delimiter, $trim_fields) {
            $fields = $trim_fields ? array_map('trim', explode($delimiter, $line)) : explode($delimiter, $line);
			if(empty($fields) || empty($fields[0]) || empty($fields[1]))
				return;

            return array_map(
                function ($field) {
                    return str_replace('!!Q!!', '"', utf8_decode(urldecode($field)));
                },
                $fields
            );
        },
        $lines
    );
}
?>
<!DOCTYPE html>
<html>
  <head>
  	<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  	<title>The Matrix going Postal</title>
    <link rel="stylesheet" href="styles/default.css">
    <script src="https://maps.googleapis.com/maps/api/js?v=3&sensor=false&key=PUT_KEY_HERE"></script>
    <script type="text/javascript" src="js/jquery-2.0.3.min.js"></script>
    <script type="text/javascript">var amount = <?php echo $amountOfPostalCodes ?>;</script>
    <script type="text/javascript" src="js/default.js"></script>
  </head>
  <body>
	<h1>The Matrix going postal</h1>

	<form method="post" enctype="multipart/form-data">
		<label>CSV:</label>
		<input type="file" name="csvfile" />
		<input type="submit" value="Upload CSV" />
	</form>

	<form method="get" id="rowcount">
		<label>Aantal:</label>
		<input type="text" name="amount" />
		<input type="submit" value="Zet rijen" />
	</form>

  	<form action="write_excel.php" method="post">
  		<input type="button" id="process" value="Bereken de afstanden" />
  		<input type="submit" value="Schrijf naar een Excel bestand" id="write_excel_submit" />
  		<input type="button" value="Help!!!" id="helpbtn" />

		<div class="help hidden">
			<ul>
				<li>
					<b>CSV:</b>
					<div>Met dit veld kan een CSV bestand met postcodes worden geupload. Dit CSV bestand bevat per rij een postode voor de verticale as (de 1e kolom) en 1 voor de horizontale (de 2e kolom).</div>
				</li>
				<li>
					<b>Aantal:</b>
					<div>Met dit veld kan opgegeven worden hoeveel rijen en kolommen er getoond moeten worden voor handmatige invoer op deze website.</div>
				</li>
				<li>
					<b>Bereken de afstanden:</b>
					<div>Met deze knop zal het proces gestart worden dat de afstanden berekend voor de intersectie van de postcodes in de matrix. Afhankelijk van het aantal postcodes kan dit proces veel tijd in beslag nemen.</div>
				</li>
				<li>
					<b>Schrijf naar een Excel bestand:</b>
					<div>De getoonde matrix op het scherm zal weggeschreven worden naar een Excel bestand (in Excel 2007 formaat). Let dus op dat je deze knop niet voortijdig aanklikt wanneer de afstanden nog berekend worden.</div>
				</li>
			</ul>
		</div>

		<div id="progressbar" class="hidden">
			<div class="done"></div>
			<div class="percentage hidden"></div>
		</div>

    	<table>
    		<?php for($rowIndex = 0; $rowIndex <= $amountOfPostalCodes; $rowIndex++) : ?>
    		<tr>
				<td<?php echo ($rowIndex == 0 && $cellIndex == 1 ? ' class="empty"' : null) ?>>
					<?php if($rowIndex != 0) : ?>
					<!-- Vertical inputs -->
					<input type="text" name="vertical[<?php echo $rowIndex ?>]" id="vertical<?php echo $rowIndex ?>" value="<?php echo (isset($csv) ? str_replace(' ', '', $csv[$rowIndex - 1][0]) : null) ?>" />
					<?php elseif($rowIndex != 0 && $cellIndex != 1) : ?>
					<input type="text" name="row[<?php echo $rowIndex ?>][<?php echo $cellIndex ?>]" id="row[<?php echo $rowIndex ?>][<?php echo $cellIndex ?>]" class="noborder" />
					<?php endif ?>
				</td>

    			<?php for($cellIndex = 1; $cellIndex <= $amountOfPostalCodes; $cellIndex++) : ?>
					<td id="row_<?php echo $rowIndex ?>_cell_<?php echo $cellIndex ?>">
						<?php if($rowIndex == 0) : ?>
						<!-- Horizontal inputs -->
						<input type="text" name="horizontal[<?php echo $cellIndex ?>]" id="horizontal<?php echo $cellIndex ?>" value="<?php echo (isset($csv) ? str_replace(' ', '', $csv[$cellIndex - 1][1]) : null) ?>" />
						<?php else : ?>
						<input type="text" name="row[<?php echo $rowIndex ?>][<?php echo $cellIndex ?>]" id="row[<?php echo $rowIndex ?>][<?php echo $cellIndex ?>]" class="noborder" />
						<?php endif ?>
					</td>
    			<?php endfor ?>
    		</tr>
    		<?php endfor ?>
    	</table>
	</form>
  </body>
</html>